﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore;
using Traceability_2203.Common.Domains;
using Traceability_2203.Common.Dtos;
using Traceability_2203.Common.Infrastructure.Interfaces;
using Traceability_2203.Enum;

namespace Traceability_2203.Bais.Api.Application.Commands.User
{
    public class UserSearchHandler : IRequestHandler<UserSearchCommand, Result<List<UserDto>>>
    {
        private readonly IBaseRepository<Users> userRepository;
        private readonly ILogger<UserCreateHandler> logger;
        private readonly IMapper mapper;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="userBaseRepository">用户仓储</param>
        public UserSearchHandler(IBaseRepository<Users> userRepository,
            ILogger<UserCreateHandler> logger,
            IMapper mapper)
        {
            this.userRepository = userRepository;
            this.logger = logger;
            this.mapper = mapper;
        }

        /// <summary>
        /// 显示查询
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task<Result<List<UserDto>>> Handle(UserSearchCommand request, CancellationToken cancellationToken)
        {
            var result = new Result<List<UserDto>> { Code = (int)CommonErrorCode.Search };
            try
            {
                var userList = await (await userRepository.GetAll()).ToListAsync();
                var list = mapper.Map<List<UserDto>>(userList);
                result.Data = list;
            }
            catch (Exception ex)
            {
                logger.LogError("显示查询用户异常" + ex.Message);
            }
            return result;
        }
    }
}
